(function ($, _window, undefined) {
  $(document).ready(function () {

      // Remove messages on form reset
      $("#my_profile").on('reset', function (event) {
          $('#success_message').removeClass("error");
          $('#registration_error_message').removeClass("error");
          $('#errors_below_message').removeClass("error");
          // Remove any existing 'errorIndicator'.

          // Remove address validation error indicator
          $(".errorImg").remove();

          // Reset email status
          $(".error-inline").remove();
          $(".success-inline").remove();
      });
    
    // When Safari Autopopulates the password field set it to blank
    // if ($('#password').length > 0) {

    //   if ($('#objBody_content_0_pagecontent_0_txtEmail').length > 0) {
    //     setTimeout(function () {
    //       $('#objBody_content_0_pagecontent_0_txtEmail').removeAttr("readonly");
    //     }, 250);
    //   }

    //   setTimeout(function () {
    //     $('#password').val("");
    //   }, 250);
    // }


    // Configurable address validation options to display supported countries and setting the default selected country.
    var addressOptions = {
        singleline: {
          supportedCountries: ["USA"],
          defaultCountry: "USA"
        }
      },
      elements = {
        emailBox: $('#objBody_content_0_pagecontent_0_txtEmail').length > 0 ? $('#objBody_content_0_pagecontent_0_txtEmail') : $('#registration-email-field'),
        searchContainer: "#searchContainer",
        success: ".success",
        buttonDiv: "#buttonDiv",
        submitButton: "#submit",
        resetButton: "#reset",
        addressStatus: "#addressStatus"
      },
      countryMapping = {
        "United Kingdom": "GBR",
        "United States of America": "USA",
        "Canada": "CAN"
      };



    // Load the plugins.
    function load() {
      var inlineMode = $.prototype.verificationSearch == undefined ? true : false,
        $emailPlugin = null,
        $addressPlugin = null;

      // Email plugin.
      if ($.prototype.emailValidate) {
        $emailPlugin = new emailValidation(
          $(elements.emailBox), {
            inlineMode: true
          });
      }

      if ($.prototype.verificationSearch) {
        // singleline.
        $addressPlugin = initializeVerificationAddressSearch();
      }
    }

    function isNullOrWhiteSpace(str) {
      return str == null || str.replace(/\s/g, '').length < 1;
    }

    // Initialize singleline address search.
    //function initializeSingleLineAddressSearch() {

    //    // Initialize the singleline plugin.
    //    return $(elements.searchContainer).singlelineSearch({
    //        onSuccess: populateAddress
    //    });
    //};

    function initializeVerificationAddressSearch() {
      // Add Supported Countries.
      //addCountry(addressOptions.verification);

      // Initialize the verification plugin.
      return $(elements.searchContainer).verificationSearch({
        onSuccess: populateAddress
      });
    }

    // Populate addresses.
    function populateAddress(data) {
      if (data && $.isArray(data.fields)) {
        var country = data.fields.pop();
        var $addresses = $(elements.inputAddress);
        var $country = $(elements.inputCountry);

        $.each(data.fields, function (index, value) {
          var $current = $($addresses[index]);
          var content = $.trim(value.content);

          $current.val(content);
          $current.addClass("success");
        });

        $country.val(countryMapping[country.content]);
        $country.addClass("success");

        $(elements.addressStatus).remove();
        $(elements.buttonDiv).after('<span id="addressStatus" class="successImg">Verified</span>');

        // Store returned address to page.
        var addressContent = constructAddressContent();

        // Bind return address events.
        bindReturnedAddressEvents(addressContent);
      }
    }

    // construct address array base on element values.
    function constructAddressContent() {
      var $returnedAddress = $(elements.inputAddress + ", " + elements.inputCountry);
      var addressContent = [];

      $returnedAddress.each(function () {
        var value = $.trim($(this).val());
        addressContent.push(value);
      });

      return addressContent;
    }

    // bind input address and input country events.
    function bindReturnedAddressEvents(addressContent) {
      var $inputAddress = $(elements.inputAddress);

      $inputAddress.on("keyup input change", null, addressContent, function (event) {
        handleAddressChange.call($(this), event.data);
      });
    }

    function handleAddressChange(content) {
      var $this = $(this);
      var updatedContent = constructAddressContent();
      var isChanged = false;

      if (updatedContent.length === content.length) {
        for (i = 0; i < updatedContent.length; i++) {
          if (updatedContent[i] !== content[i]) {
            isChanged = true;
            break;
          }
        }
      } else {
        isChanged = true;
      }

      if (isChanged && $this.hasClass("success")) {
        $(elements.inputAddress).removeClass("success");
        $(elements.inputCountry).removeClass("success");

        $(elements.addressStatus).addClass("hidden");
      } else if (!isChanged && !$this.hasClass("success")) {
        $(elements.inputAddress).addClass("success");
        $(elements.inputCountry).addClass("success");

        $(elements.addressStatus).removeClass("hidden");
      }
    }

    load(); 
  });


})(jQuery, window);